//npm包放在最前面
const bcrypt = require('bcryptjs')
// 使用sequlize生成表
const { sequelize } = require('../../core/db')
const { Sequelize, Model } = require('sequelize')

class User extends Model {
    //添加校验用户名与密码方法
    static async verifyEmailPassword(email, plainPassword) {
        const user = await User.findOne({
            where: {
                email
            }
        })
        if (!user) {
            throw new global.errs.AuthFailed('账号不存在')
        }
        const correct = bcrypt.compareSync(plainPassword, user.password)//bcrypt自带比较方法,第一个是打算比较的明文密码,第二个是加密后的密码
        if (!correct) {
            throw new global.errs.AuthFailed('密码不正确')
        }
        return user
    }
}
User.init({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    nickname: Sequelize.STRING,
    email: {
        type: Sequelize.STRING(128),
        unique: true,
    },
    password: {
        //扩展 观察者模式的应用 观察password ,变化就执行
        //ES6 Reflect
        type: Sequelize.STRING,
        set(val) {
            const salt = bcrypt.genSaltSync(10) //参数=>加密位数=>计算成本=>不宜过大会耗性能
            const psw = bcrypt.hashSync(val, salt)//两串一样的明文,加密之后也不会一样,防范彩虹攻击
            this.setDataValue('password', psw)//指定字段设值
        }
    },
    openid: {
        type: Sequelize.STRING(64),
        unique: true,
    },

}, {
    sequelize,
    tableName: 'user'
})

module.exports = {
    User
}
